<template>
    <el-dialog :title="currentSite?'编辑车站':'添加车站'" :visible.sync="showDialog_" custom-class='dialog_right dialogScroll_add MkAddSite' top="0%" @close='closeDialog("addForm")' @open='openDialog'>
      <el-scrollbar :wrapStyle="[{maxHeight:(bodyHeight-200)+'px'}]">
        <el-form :model="addForm.formItem" :rules="addForm.rules" ref="addForm" label-width="80px">
          <input type="text" style="display:none" />
          <el-form-item  label="车站名称" prop='name'>
            <el-input v-model="addForm.formItem.name" :maxlength="8" placeholder='请输入车站名称（必填）'size=""></el-input>
          </el-form-item>
          <el-form-item  label="简称" prop='shortName'>
            <el-input v-model="addForm.formItem.shortName":maxlength="8" placeholder='请输入简称（必填）'size=""></el-input>
          </el-form-item>

          <el-form-item label="所属城市" prop="cityArr">
            <el-cascader
              placeholder="请选择所属城市（必选）"
              :options="provinceTree"
              v-model="addForm.formItem.cityArr"
              @active-item-change="handleProvinceChange"
              :props="props"
            ></el-cascader>
          </el-form-item>

          <el-form-item  label="乘车地址" prop='address'>
            <el-input v-model="addForm.formItem.address" placeholder='请输入乘车地址（必填）'size=""></el-input>
          </el-form-item>
          <el-form-item label="站点图片" prop="imageIds">
            <el-upload class="upload-file uploadStyle2"
                       :action="'/upload/images.json'"
                       :on-success="handleSuccess"
                       :on-remove="handleRemove"
                       :on-change="handleChange"
                       :file-list="fileList"
                       ref="uploadComponent"
                       :before-upload='beforeAvatarUpload'
                       list-type="picture-card"
                       accept=".jpeg, .jpg, .png, .gif" name="images">
              <i class="el-icon-plus" ref="uploadFileBtn"></i>
            </el-upload>
            <p style="color:#83a0a5;font-size:14px;">建议上传不大于800宽度，不大于1200高度的图片</p>
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <div slot="footer" class="dialog-footer footerStyle">
          <el-button type="primary" class="btn-primary" :disabled = 'isSubmitBtnDisabled' @click='submitForm("addForm")' v-loading.fullscreen.lock="fullscreenLoading">保存</el-button>
          <el-button  type='primary'class='btn-cancel' :disabled = "isSubmitBtnDisabled"  @click="showDialog_ = false" size=''>取消</el-button>
      </div>
    </el-dialog>
</template>

<script>
import routeService from '../../../services/route'
//import * as constants from '../../../utils/constants'
import { mapState } from 'vuex'
export default {
  name: 'MkAddSite',
  components: {

  },
  props: ['showDialog','currentSite'],
  computed: mapState({
    bodyHeight: state => state.global.bodyHeight,
    provinceSelect: state => state.route.provinceSelect
  }),
  methods: {
    handleProvinceChange(val) {
      if(val) {
        let currentIndex;
        let currentProvince = this.provinceTree.filter((item,index) => {
          if(item.id == val[0]) {
            currentIndex = index
          }
          return item.id == val[0];
        })
        if(currentProvince[0].children.length == 0) {
          routeService.loadProvinceAndCitySelect({fields:'id,name,parentId,type',parentId:val[0]}, data => {
            this.provinceTree[currentIndex].children = data.data;
          })
        }
      }
    },
    beforeAvatarUpload(file) {

    },
    handleRemove(file,fileList) {
      let fileId = file.fileId?file.fileId:file.response.data[0].fileId;
      routeService.deleteFileServer({fileId:fileId},data=>{
        this.$message.success('删除成功');
        this.fileList = fileList;
        if (fileList.length > 4) {
          this.$refs.uploadFileBtn.parentElement.style.display = 'none';
        } else {
          this.$refs.uploadFileBtn.parentElement.style.display = '';
        }
      })
    },
    handleChange(file, fileList) {

    },
    handleSuccess(response,file,fileList) {
      this.fileList = fileList;
      if (fileList.length > 4) {
        this.$refs.uploadFileBtn.parentElement.style.display = 'none';
      } else {
        this.$refs.uploadFileBtn.parentElement.style.display = '';
      }
    },
    closeDialog(formName) {
      this.$refs[formName].resetFields();
      this.fileList = [];
      this.$emit('closeDialog',this.isRefresh);
    },
    openDialog() {
      this.isRefresh = 'no';
      this.isSubmitBtnDisabled = false;
      this.fileList = [];
      if(this.currentSite) {
        let form = this.addForm.formItem;
        let currentSite = this.currentSite;
        form.name = currentSite.name;
        form.shortName = currentSite.shortName;
        form.address = currentSite.address;
        var fileArr=[];
        for(var i= 0;i<currentSite.images.length;i++) {
          let item = currentSite.images[i];
          fileArr.push({url:item.accessUrl,fileId: item.fileId})
        }
        this.fileList = fileArr;

        routeService.loadProvinceAndCitySelect({fields:'id,name,parentId,type',parentId:currentSite.cityIdPath[0]}, data => {
          this.provinceTree.forEach((item,index) => {
            if(item.id == currentSite.cityIdPath[0]) {
              this.provinceTree[index].children = data.data;
              form.cityArr = currentSite.cityIdPath;
            }
          })

        })
      }
      this.$nextTick(function() {
        if (this.fileList.length > 4) {
          this.$refs.uploadFileBtn.parentElement.style.display = 'none';
        } else {
          this.$refs.uploadFileBtn.parentElement.style.display = '';
        }
      })
    },
    submitForm(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let form = this.addForm.formItem;
          let fileArr = [];

          for(let i = 0;i<this.fileList.length;i++) {
            var item = this.fileList[i];
            if(item.fileId) {
              fileArr.push(item.fileId)
            }else{
              fileArr.push(item.response.data[0].fileId)
            }
          }
          if(fileArr.length>5){
              this.$message.warning('最多上传5张图片，请删除'+(fileArr.length-5)+'张');
              return false;
          }
          let param = {
            name: form.name,
            cityId: form.cityArr[form.cityArr.length-1],
            shortName: form.shortName,
            address: form.address,
            imageIds: fileArr.join(','),
          }

          this.fullscreenLoading = true;
          this.isSubmitBtnDisabled = true;
          if(this.currentSite) {
            param.id = this.currentSite.id;
            routeService.editSite(param,(data)=>{
              this.$message.success('编辑成功');
              this.isRefresh = 'yes';
              this.showDialog_ = false;
              this.fullscreenLoading = false;
            },(data)=>{
              this.fullscreenLoading = false;
              this.isSubmitBtnDisabled = false;
            })
          }else{
            routeService.addSite(param,(data)=>{
              this.$message.success('添加成功');
              this.isRefresh = 'yes';
              this.showDialog_ = false;
              this.fullscreenLoading = false;
            },(data)=>{
              this.fullscreenLoading = false;
              this.isSubmitBtnDisabled = false;
            })
          }
        }
      })
    }
  },
  watch: {
    showDialog: function(value) {
      this.showDialog_=value;
    },
    provinceSelect: function(val) {
        console.log(val)
      for(let i = 0;i<val.length;i++) {
        this.provinceTree.push({
          id: val[i].id,
          name: val[i].name,
          children: [],
        })
      }
    }
  },
  data () {
    var validateName = (rule,val,callback) => {
      if(val.trim() == '') {
        callback("请输入车站名称");
      }else{
        if(val.length>8){
          callback('最多输入8位');
        }else{
            callback();
        }
      }
    }
    var validateShortName = (rule,val,callback) => {
      if(val.trim() == '') {
        callback("请输入简称");
      }else{
        let reg = /^[a-zA-Z]{1,8}$/
        if(!reg.test(val)){
          callback("只能输入字母,不超过8位");
        }else{
          callback();
        }
      }
    }
    let validateAddress =  (rule,val,callback) => {
      if(val.trim() == '') {
        callback("请输入乘车地址");
      }else{
        if(val.length>40){
          callback("最多输入40位");
        }else{
            callback();
        }
      }
    }
    return {
      props: {
        value: 'id',
        children: 'children',
        label:'name',
      },
      provinceTree: [],
      citySelect: [],
      fileList: [],
      isSubmitBtnDisabled: false,
      fullscreenLoading: false,
      isRefresh: 'no',
      showDialog_: this.showDialog,
      addForm: {
        formItem: {
          name: '',
          cityId: '',
          shortName:'',
          address: '',
          imageIds: '',

          cityArr: [],
        },
        rules: {
          name: {validator:validateName,trigger: 'change,blur'},
          shortName: {validator:validateShortName,trigger: 'change,blur'},
          address:{validator:validateAddress,trigger: 'change,blur'},
          cityArr: {required:true,message:'请选择所属城市',type:'array',trigger:'change,blur'}
        }
      }

    }
  }
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang='less'>
 @import '../../../assets/style/main.less';
  .MkAddSite{
    .upload-file {
      .el-upload--picture-card{
        background:#fff;
      }

      .el-upload-list--picture-card .el-upload-list__item{
         width:120px;
        height:120px;
        margin-bottom:20px;
        margin-right:20px;
      }
      .el-upload--picture-card{
        width:120px;
        height:120px;
        .el-icon-plus{
          position: relative;
          top:-10px;
        }
      }
    }
  }
</style>
